<template>
  <div class="contain">
    <div class="title">您好！</div>
    <div class="sub-title">欢迎登录XXXX管理平台</div>
    <div class="login-wrap">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" size="default">
        <div class="login-form">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="ID" autofocus prefix-icon="el-icon-user" clearable />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              :placeholder="$t('login.password')"
              show-password
              maxlength="30"
              show-word-limit
              autocomplete="new-password"
              prefix-icon="el-icon-lock"
              clearable
              @keypress.enter.native="handleLogin"
            />
          </el-form-item>
        </div>
        <el-button
          type="primary"
          style="width: 100%; height: 40px; border-radius: 20px; margin-top: 50px"
          size="medium"
          @click.native.prevent="handleLogin"
          >立即登录<i class="el-icon-right"></i
        ></el-button>
      </el-form>
    </div>
  </div>
</template>
<script>
import { encrypt } from '@/utils/rsaEncrypt'
import { getPublicKey } from '@/api/user'
import { getSysUI } from '@/utils/auth'
import { changeFavicon, showMultiLoginMsg } from '@/utils/index'
import { initTheme } from '@/utils/ThemeUtil'
// import PluginCom from '@/components/vis/system/plugin/plugin-com'
import Cookies from 'js-cookie'
export default {
  name: 'Login',
  // components: { PluginCom },
  data() {
    return {
      logo: require('../../assets/images/logo.png'),
      loginForm: {
        loginType: 0,
        username: '',
        password: '',
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: this.$t('commons.input_id') }],
        password: [{ required: true, trigger: 'blur', message: this.$t('commons.input_pwd') }],
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      uiInfo: null,
      loginImageUrl: null,
      loginLogoUrl: null,
      axiosFinished: false,
      loginTypes: [0],
      contentShow: false,
      clearLocalStorage: ['panel-main-tree', 'panel-default-tree', 'chart-tree', 'dataset-tree'],
      defaultType: 0,
      showFoot: false,
      footContent: '',
      imgAppShow: true,
    }
  },
  computed: {
    msg() {
      return this.$store.state.user.loginMsg
    },
    qrTypes() {
      return (this.loginTypes && this.loginTypes.filter((item) => item > 3 && item < 7)) || []
    },
    radioTypes() {
      return (this.loginTypes && this.loginTypes.filter((item) => item < 4 || item > 6)) || []
    },
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true,
    },
  },
  beforeCreate() {
    initTheme()

    getPublicKey().then((res) => {
      if (res.success && res.data) {
        // 保存公钥
        localStorage.setItem('publicKey', res.data)
      }
    })
  },

  mounted() {
    // this.loading = false
  },

  created() {
    this.$store
      .dispatch('user/getUI')
      .then((res) => {
        this.axiosFinished = true
        this.showLoginImage(res)
      })
      .catch((err) => {
        console.error(err)
      })
    let msg = Cookies.get('OidcError')
    if (msg) {
      msg = msg.replace('+', '')
      this.$error(msg)
    }
    this.clearOidcMsg()

    this.clearLarkMsg()

    if (Cookies.get('LarksuiteError')) {
      this.$error(Cookies.get('LarksuiteError'))
    }
    this.clearLarksuiteMsg()
    showMultiLoginMsg()
    this.contentShow = true
  },

  methods: {
    setDefaultType() {
      if (this.loginTypes.includes(this.defaultType)) {
        this.loginForm.loginType = this.defaultType
        this.$nextTick(() => {
          this.changeLoginType(this.loginForm.loginType)
        })
      }
    },
    clearOidcMsg() {
      Cookies.remove('OidcError')
      Cookies.remove('IdToken')
    },
    clearWecomMsg() {
      Cookies.remove('WecomError')
    },
    clearDingtalkMsg() {
      Cookies.remove('DingtalkError')
    },
    clearLarkMsg() {
      Cookies.remove('LarkError')
    },
    clearLarksuiteMsg() {
      Cookies.remove('LarksuiteError')
    },
    showLoginImage(uiInfo) {
      this.uiInfo = getSysUI()
      if (!this.uiInfo || Object.keys(this.uiInfo).length === 0) {
        this.uiInfo = uiInfo
      }
      if (this.uiInfo['ui.loginImage'] && this.uiInfo['ui.loginImage'].paramValue) {
        this.loginImageUrl = '/system/ui/image/' + this.uiInfo['ui.loginImage'].paramValue
      }
      if (this.uiInfo['ui.loginLogo'] && this.uiInfo['ui.loginLogo'].paramValue) {
        this.loginLogoUrl = '/system/ui/image/' + this.uiInfo['ui.loginLogo'].paramValue
      }

      if (this.uiInfo['ui.favicon'] && this.uiInfo['ui.favicon'].paramValue) {
        const faviconUrl = '/system/ui/image/' + this.uiInfo['ui.favicon'].paramValue
        changeFavicon(faviconUrl)
      }
      if (this.uiInfo['ui.showFoot'] && this.uiInfo['ui.showFoot'].paramValue) {
        this.showFoot =
          this.uiInfo['ui.showFoot'].paramValue === true || this.uiInfo['ui.showFoot'].paramValue === 'true'
        if (this.showFoot) {
          const content = this.uiInfo['ui.footContent'] && this.uiInfo['ui.footContent'].paramValue
          this.footContent = content
        }
      }
    },
    initCache() {
      this.clearLocalStorage.forEach((item) => {
        localStorage.removeItem(item)
      })
    },

    handleLogin() {
      this.initCache()
      this.clearOidcMsg()
      this.clearWecomMsg()
      this.clearDingtalkMsg()
      this.clearLarkMsg()
      this.clearLarksuiteMsg()
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          console.log(this.loginForm.loginType)
          const user = {
            username: encrypt(this.loginForm.username),
            password: encrypt(this.loginForm.password),
            loginType: this.loginForm.loginType,
          }
          this.$store
            .dispatch('user/login', user)
            .then(() => {
              this.$router.push({ path: '/m-index' })
              this.loading = false
            })
            .catch((e) => {
              this.loading = false
              e?.response?.data?.message?.startsWith('MultiLoginError') && this.showMessage()
            })
        } else {
          return false
        }
      })
    },
    showMessage() {
      showMultiLoginMsg()
    },
    changeLoginType(val) {
      if (val !== 2 && val !== 7) return
      this.clearOidcMsg()
      this.clearLarksuiteMsg()
      this.$nextTick(() => {})
    },
  },
}
</script>
<style lang="scss" scoped>
.contain {
  width: 100vw;
  height: 100vh;
  background: url('~@/assets/m-image/login-bg.png') no-repeat;
  background-size: 100% 100%;
}

.title {
  font-size: 36px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: #0073e5;
  line-height: 36px;
  padding: 117px 36px 0;
}

.sub-title {
  font-size: 20px;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  color: #262626;
  line-height: 20px;
  padding: 13px 36px 0;
}

.login-wrap {
  margin: 32px 16px 0;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.8) 0%, #ffffff 100%);
  box-shadow: 0px 8px 24px 0px rgba(42, 185, 248, 0.2);
  border-radius: 16px;
  opacity: 0.6;
  border-image: linear-gradient(0deg, rgba(41, 179, 249, 1), rgba(54, 178, 137, 1), rgba(136, 204, 102, 1)) 0 0;
  padding: 36px 24px 32px;
}
.el-icon-right {
  margin-left: 10px;
}
</style>
